<template>
  <el-drawer 
    model-value="roleDialogVisible"
    title="分配角色"
    width="30%"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="100px">
      <el-checkbox-group v-model="form.checkedRoles">
        <el-checkbox
          v-for="role in form.roleList"
          :id="role.id + ''"
          :key="role.id"
          :label="role.id"
          name="checkedRoles"
          >{{ role.name }}</el-checkbox
        >
      </el-checkbox-group>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm(formRef)"
          >确认</el-button
        >
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-drawer>
</template>
<script lang="ts">
export default {
  name: "userRoleDialog",
};
</script>
<script setup lang="ts">
import { defineEmits, defineProps, ref, watch} from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";

import { listAll, grantRole } from "@/api/role";

// 从父组件传过来的信息参数，子组件接受
const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true,
  },
  roleDialogVisible: {
    type: Boolean,
    default: false,
    required: true,
  },
  sysRoleList: {
    type: Array,
    default: [],
    required: true,
  },
});
interface RuleForm {
  id: number;
  roleList: Array<Object>;
  checkedRoles: Array<Object>;
}

const form:any = ref<RuleForm>({
  id: -1,
  roleList: [],
  checkedRoles: [],
});

const formRef = ref<FormInstance>();

const initFormData = async (id) => {
  const res = await listAll();
  form.value.roleList = res.data.data;
  form.value.id = id;
};

watch(
  () => props.roleDialogVisible,
  () => {
    let id = props.id;
    console.log("id=" + id);
    if (id != -1) {
      form.value.checkedRoles = [];
      props.sysRoleList.forEach((item: any) => {
        form.value.checkedRoles.push(item.id);
      });
      console.log("checkedRoles", props.sysRoleList);
      initFormData(id);
    }
  }
);

const emits = defineEmits(["update:modelValue", "initUserList"]);

const handleClose = () => {
  emits("update:modelValue", false);
};

const handleConfirm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let result = await grantRole({
        userId: form.value.id,
        roleIds: form.value.checkedRoles,
      });
      let data = result.data;
      if (data.code == 200) {
        ElMessage.success(data.msg);

        emits("initUserList");
        handleClose();
      } else {
        ElMessage.error("角色分配失败,请联系管理员！");
      }
    } else {
      console.log("fail");
    }
  });
};
</script>